package com.szt.sy.config.async;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.szt.sy.util.date.DateUtil;
import com.szt.sy.util.json.JsonUtils;

/***
 * async 配置类
 * 
 * @author wwy
 *
 */
@Configuration
@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {
	
	@Override
	public Executor getAsyncExecutor() {
		// 设置线程池大小
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		int processors = Runtime.getRuntime().availableProcessors();
		executor.setCorePoolSize(processors);
		executor.setMaxPoolSize(processors * 2);
		executor.setQueueCapacity(processors * 5);
		executor.setThreadNamePrefix("CustomAsyncExecutor-");
		executor.initialize();
		return executor;
	}
	
	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new CustomAsyncUncaughtExceptionHandler();
	}
	
	/***
	 * 自定义异步任务异常处理类
	 * 
	 * @author wwy
	 *
	 */
	private static class CustomAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
		
		private static final Logger LOG = LoggerFactory.getLogger(CustomAsyncUncaughtExceptionHandler.class);
		
		@Override
		public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
			String uuid = IdWorker.get32UUID();
			LOG.error("id:{},执行异步任务异常,时间:{},类:{},方法:{},其他参数:{}", uuid, DateUtil.getTime(),
					arg1.getDeclaringClass().getName(), arg1.getName(), JsonUtils.beanToString(arg2));
			LOG.error("id:" + uuid + ",具体异常信息:", arg0);
		}
		
	}
}
